<template>
	<uni-forms ref="form" :modelValue="form" :rules="rules" label-position="top">
		<view>
			<uni-card class="handle-card">
				<uni-forms-item required label="故障描述" name="faultAnalysis">
					<textarea v-model="form.faultAnalysis" placeholder="请详细描述故障情况..." focus="true" />
				</uni-forms-item>
<!-- 				<uni-forms-item class="data-select" required label="故障部位" name="faultLocation">
					<input type="text" v-model="form.faultLocation" placeholder="请选择故障部位" />
				</uni-forms-item> -->

				<uni-forms-item label="现场照片" name="sitePhotos" required>
					<uni-file-picker v-model="form.sitePhotos" limit="9" title="最多选择9张图片" :auto-upload="false"
						@select="fileUpload">
					</uni-file-picker>
				</uni-forms-item>
			</uni-card>
			<uni-card>
				<uni-forms-item label="是否能当场修复" label-width="300" required name="SiteRepair">
					<uni-data-checkbox v-model="form.siteRepair" :localdata="repair" />
				</uni-forms-item>
			</uni-card>
			<view class="button-select">
				<button type="primary" @click="handleButton">维修报告</button>
			</view>
		</view>
	</uni-forms>
</template>

<script>
	import {
		getOrder,
		updateOrder
	} from "@/api/repairManage/order.js"
	import {
		getToken
	} from '@/utils/auth'
	import {
		getRepairReportByOrderId,
		addRepairReport,
		updateRepairReport
	} from "@/api/repairManage/repairer.js"
	export default {
		data() {
			return {
				// 订单ID
				orderId: undefined,
				// 订单信息
				orderInfo: {

				},
				form: {
					// 维修报告信息
					repairReport: undefined,
					// 故障描述
					faultAnalysis: "",
					// 故障部位
					faultLocation: "",
					// 现场照片
					sitePhotos: [],
					// 是否当场修复
					SiteRepair: '',
				},

				repair: [{
					text: '能',
					value: '1'
				}, {
					text: '不能',
					value: '2'
				}],
				// 表单校验
				rules: {
					faultAnalysis: {
						rules: [{
							required: true,
							errorMessage: '故障描述不能为空'
						}]
					},
					faultLocation: {
						rules: [{
							required: true,
							errorMessage: '故障部位不能为空'
						}]
					},
					siteRepair: {
						rules: [{
							required: true,
							errorMessage: '是否能当场修复不能为空'
						}]
					},
					sitePhotos: {
						rules: [{
							type: 'array',
							required: true,
							errorMessage: '现场照片不能为空'
						}]
					},
				}
			}
		},
		onLoad(options) {
			console.log("========= 现场诊断 =========");
			this.orderId = options.orderId
		},
		created() {
			this.getOrderInfo();
		},
		methods: {
			// 获取 订单信息
			getOrderInfo() {
				const _this = this
				if (this.orderId == undefined || this.orderId == "") {
					uni.navigateBack()
				} else {
					getRepairReportByOrderId(this.orderId).then(res => {
						if (res != undefined && res != null && res.data != null) {
							this.repairReport = res.data
							this.form.faultAnalysis = res.data.faultAnalysis
							this.form.faultLocation = res.data.faultLocation
							this.form.sitePhotos = res.data.sitePhotos.split(",").map(item => _this
								.createFileObject(item))
							this.form.siteRepair = res.data.siteRepair
						}
					}).then(() => {
						if (this.repairReport == undefined) {
							getOrder(this.orderId).then(res => {
								this.form.orderInfo = res.data
								this.form.faultAnalysis = res.data.faultDescription
							})
						}
					})
				}

			},
			createFileObject(url) {
				if (typeof url !== 'string' || url.trim() === '') {
					return {
						'url': '',
						'fileName': ''
					}
				}
				console.log(url);
				const fullUrl = url.startsWith('http') ? url : getApp().globalData.config.baseUrl + url;
				console.log(fullUrl);
				return {
					"url": fullUrl,
					"fileName": url
				};
			},
			// 文件上传
			fileUpload(e) {
				const tempFilePaths = e.tempFilePaths;
				const _this = this;
				uni.uploadFile({
					url: getApp().globalData.config.baseUrl + '/common/upload',
					//你的上传文件的接口地址：若依的一般就是这个
					filePath: tempFilePaths[0],
					name: 'file',
					header: {
						Authorization: "Bearer " + getToken()
					},
					success: (res) => {
						try {
							const resData = JSON.parse(res.data);
							const imgUrls = resData.fileName;
							if (typeof imgUrls !== 'string') {
								console.error("上传结果格式不正确:", imgUrls);
								return;
							}
							const site = _this.createFileObject(imgUrls);
							_this.form.sitePhotos.push(site);
						} catch (err) {
							console.error("文件上传解析失败:", err, res.data);
						}
					}
				});
			},
			changePart(res) {
				console.log(res);
			},
			handleButton() {
				console.log("========= 维修报告 =========");
				this.$refs.form.validate().then(res => {
					const date = new Date()
					const timestamp = date.getTime()
					if (this.repairReport == undefined) {
						console.log("========= 创建维修报告 =========");
						console.log(this.form.sitePhotos);
						const sitePhotos = this.form.sitePhotos.flatMap(item => item.fileName)
						console.log(sitePhotos);
						const addDate = {
							"orderId": this.orderId,
							"orderNo": this.orderInfo.orderNo,
							"reportNo": timestamp,
							"faultAnalysis": this.form.faultAnalysis,
							"faultLocation": this.form.faultLocation,
							"sitePhotos": sitePhotos.join(","),
							"siteRepair": this.form.siteRepair
						}
						addRepairReport(addDate).then(res => {
							updateOrder({
								'orderId': this.orderId,
								'orderStatus': "2"
							}).then(res => {
								console.log(res);
								this.$tab.navigateTo("/pages/indent/maintain?orderId=" + this
									.orderId)
							})
						})
					} else if (this.repairReport != undefined && this.repairReport.reportId != undefined) {
						console.log("========= 更新维修报告 =========");
						const sitePhotos = this.form.sitePhotos.flatMap(item => item.fileName)
						this.repairReport.sitePhotos = sitePhotos.join(",")
						this.repairReport.faultAnalysis = this.form.faultAnalysis
						this.repairReport.faultLocation = this.form.faultLocation
						this.repairReport.siteRepair = this.form.siteRepair
						updateRepairReport(this.repairReport).then(res => {
							updateOrder({
								'orderId': this.orderId,
								'orderStatus': "2"
							}).then(res => {
								console.log(res);
								this.$tab.navigateTo("/pages/indent/maintain?orderId=" + this
									.orderId)
							})
						})
					} else {
						this.$modal.msgError("操作失败")
						this.$tab.navigateBack()
					}

				}).catch(err => {
					console.log(err);
					this.$modal.msgError(err[0].errorMessage)
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: #FFFFFF;

	}

	.handle-card {
		.data-select {
			z-index: 1000;
		}
	}

	.button-select {
		margin: auto;
		width: 90%;
	}
</style>